<!-- APP管理>广告发布 -->
<template>
  <div class="app-container">
    <el-tabs :active-name="activeName" @tab-click="handleTabClick">
      <el-tab-pane label="C端小程序" name="1"></el-tab-pane>
      <el-tab-pane label="B端小程序" name="2"></el-tab-pane>
    </el-tabs>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="位置" prop="spaceId">
        <el-select
          v-model="queryParams.location"
          placeholder=""
          clearable
          size="small"
          style="width: 250px"
        >
          <el-option
            v-for="(item, index) in dict.type.ad_location"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="cyan"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
        >重置
        </el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button
            size="mini"
            circle
            icon="el-icon-refresh"
            @click="handleQuery"
          />
        </el-tooltip>
        <el-tooltip
          class="item"
          effect="dark"
          :content="showSearch ? '隐藏搜索' : '显示搜索'"
          placement="top"
        >
          <el-button
            size="mini"
            circle
            icon="el-icon-search"
            @click="showSearch = !showSearch"
          />
        </el-tooltip>
      </div>
    </el-row>
    <el-table v-loading="loading" :data="adList">
      <el-table-column
        label="标题"
        align="center"
        prop="title"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="图片"
        align="center"
        prop="name"
      >
        <template slot-scope="scope">
          <div>
            <img class="ad-img" :src="scope.row.img" alt="" mode="widthFix" style="width: 100px;height: 100px"/>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        label="类型"
        align="center"
        prop="publish"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ad_type"
            :value="scope.row.bannerType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="位置"
        align="center"
        prop="expire"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ad_location"
            :value="scope.row.location"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="区域展示设置"
        align="center"
        prop="sortNumber"
        :show-overflow-tooltip="true"
        v-if="activeName === '1'"
      >
        <template slot-scope="scope">
          <span>{{ setLocationMap[scope.row.location] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="排序"
        align="center"
        prop="sortNumber"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="350"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetail(scope.row)"
          >详情
          </el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />
    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" :disabled="isDetail">
        <el-form-item label="图片" prop="img">
          <el-upload
            style="margin-top: 10px"
            class="image-uploader"
            :headers="headers"
            action="/api/common/upload"
            :show-file-list="false"
            accept=".jpg,.png"
            :on-success="onSuccess"
            :on-remove="onRemove"
          >
            <img v-if="form.img" :src="form.img" class="image"/>
            <i v-else class="el-icon-plus image-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip" v-if="form.spaceId == 28">
              只能上传jpg/png文件，且不超过500kb，长宽比例建议为 720*300
            </div>
            <div slot="tip" class="el-upload__tip" v-else>
              只能上传jpg/png文件，且不超过500kb，长宽比例为 2.5：1
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input style="width: 250px" v-model="form.title" placeholder=""/>
        </el-form-item>
        <el-form-item label="描述" prop="describe">
          <el-input
            style="width: 250px"
            v-model="form.describe"
            placeholder=""
          />
        </el-form-item>
        <el-form-item label="类型" prop="bannerType">
          <el-radio-group v-model="form.bannerType">
            <el-radio
              :label="item.value"
              v-for="(item, index) in dict.type.ad_type"
              :key="index"
            >{{ item.label }}
            </el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告链接" prop="link" v-if="form.bannerType != 1">
          <el-input
            style="width: 250px"
            v-model="form.link"
            placeholder="请输入广告链接"
          />
          <div>选择外链时，地址格式请按照https://xxx.com 或 http://xxx.com 例如：http://baidu.com</div>
        </el-form-item>
        <el-form-item label="位置" prop="location">
          <el-select
            v-model="form.location"
            placeholder="位置"
            clearable
            size="small"
            style="width: 250px"
          >
            <el-option
              v-for="(item, index) in dict.type.ad_location.filter(item=>{
                if(form.adType === '1'){
                  return item
                }else{
                  return item.value ==='1'
                }
              })"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="显示排序" prop="sortNumber">
          <el-input-number
            v-model="form.sortNumber"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="区域展示设置" prop="areaType" v-if="form.adType === '1'" label-width="100px">
          <el-radio-group v-model="form.areaType">
            <el-radio :label="1" label="1">全部</el-radio>
            <el-radio :label="2" label="2">指定区域</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="指定区域" prop="cityCode" v-if="form.areaType === '2'">
          <!--          <el-cascader filterable clearable ref="areaPicker" v-model="cityCode" :props="areaProps" :show-all-levels="true"-->
          <!--                       @change="handleAreaChange"></el-cascader>-->
          <el-cascader :options="areaList" filterable clearable ref="areaPicker" v-model="cityCode"
                       :props="{multiple: true, emitPath: false, showAllLevels: true, label: 'name', value: 'id'}"
                       :show-all-levels="true"
                       @change="handleAreaChange"></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="!isDetail">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  advertisementPages,
  addAdvertisement,
  updateAdvertisement,
  delAdvertisement,
  findAdvertisementById,
  advertisementAudit,
  advertisementStatus,
  adspaceFindAll,
} from "@/api/app/advertisement";
import {getToken} from "@/utils/auth";
import {areaInfo, listArea} from "@/api/system/config";

import cityData from './city'

export default {
  dicts: ["ad_type", "ad_location"],
  name: "adIndex",
  components: {},
  data() {
    return {
      activeName: "1",
      headers: {
        Authorization: `Bearer   ` + getToken(),
      },
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 参数表格数据
      adList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否详情页
      isDetail: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        location: undefined,
        auditorStatus: undefined,
        status: undefined,
        adType: "1" //广告类型：1.C端小程序；2.B端小程序
      },

      cityCode: [], //区域编码
      areaList: [], //区域列表
      options: cityData, //区域编码
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [{required: true, message: "标题不能为空", trigger: "blur"}],
        bannerType: [
          {required: true, message: "类型不能为空", trigger: "blur"},
        ],
        img: [{required: true, message: "广告图不能为空", trigger: "change"}],
        location: [
          {required: true, message: "位置不能为空", trigger: "change"},
        ],
        link: [
          {required: true, message: "广告链接不能为空", trigger: "blur"},
        ],
        sortNumber: [
          {required: true, message: "排序不能为空", trigger: "change"},
        ],
      },
      // 图片文件
      adImageFile: undefined,
      adspaceList: [],
      areaProps: {
        lazy: true,
        multiple: true,
        emitPath: false,
        lazyLoad(node, resolve) {
          listArea({level: node.level + 1, parentId: node.value}).then(
            (res) => {
              const areas = res.data.map((value, i) => ({
                value: value.id,
                label: value.name,
                leaf: node.level >= 1,
              }));
              resolve(areas);
            }
          );
        },
      },
      // 映射
      setLocationMap: {
        '1': '不设置',
        '2': '指定区域',
      }
    };
  },
  created() {
    this.getList();
    this.getAreaInfo()
    //this.getAdspaceList()
    console.log('cityData', cityData)
  },
  methods: {
    // 获取区域信息
    getAreaInfo() {
      areaInfo().then((res) => {
        this.areaList = res.data;
      });
    },
    handleTabClick(tab, event) {
      this.activeName = tab.name;
      this.queryParams.adType = tab.name;
      this.resetQuery();
    },
    // 获取广告位列表
    getAdspaceList() {
      adspaceFindAll().then((response) => {
        this.adspaceList = response.data;
      });
    },
    /** 查询参数列表 */
    getList() {
      this.loading = true;
      advertisementPages(this.addDateRange(this.queryParams)).then(
        (response) => {
          this.adList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        title: "",
        describe: "",
        img: "",
        bannerType: "1", //类型：1,无跳转 2,跳转内链 3,跳转外链
        location: "1", //位置：1,首页轮播 2,首页广告位
        link: "",
        sortNumber: 1, //排序
        areaType: "1", //区域展示设置类型：1.不设置；2.指定区域；
        areaName: "", //区域名称
        cityCode: "", //区域编码
        adType: this.activeName, //广告类型：1.C端小程序；2.B端小程序
      };
      this.adImageFile = undefined;

      this.resetForm("form");
      this.isDetail = false;
      this.cityCode = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 0;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.location = undefined;
      this.queryParams.title = undefined;
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加广告";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.title = "修改广告";
      findAdvertisementById(row.bannerId).then((res) => {
        this.form = res.data;
        this.open = true;
        this.$nextTick(() => {
          this.cityCode = this.form.cityCode.split(",");
        });
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      this.title = "广告详情";
      findAdvertisementById(row.bannerId).then((res) => {
        this.form = res.data;
        this.isDetail = true;
        this.open = true;
        this.$nextTick(() => {
          this.cityCode = this.form.cityCode.split(",");
        });
      });
    },
    // 区域选择
    handleAreaChange(value) {
      console.log('value', value, this.$refs['areaPicker'])
      this.form.cityCode = value.join(",");
    },
    // 日期范围
    onSuccess(response, file, fileList) {
      this.$set(this.form, "img", response.url);
    },
    onRemove() {
      this.form.houseQrCode = "";
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form);
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let form = {...this.form}
          delete form['areaList']
          if (this.form.bannerId != undefined) {
            updateAdvertisement(form).then((response) => {
              this.open = false;
              this.getList();
              this.$message({
                message: "修改成功",
                type: "success",
              });
            });
          } else {
            addAdvertisement(form).then((response) => {
              this.open = false;
              this.getList();
              this.$message({
                message: "新增成功",
                type: "success",
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const adIds = row.bannerId || this.ids;
      this.$confirm("是否确认删除该广告", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return delAdvertisement(adIds);
        })
        .then(() => {
          this.getList();
          this.$message({
            message: "删除成功",
            type: "success",
          });
        })
        .catch(function () {
        });
    },
    // 上下架
    updateStatus(row) {
      let statusName = row.status == 1 ? "下架" : "上架";
      let status = row.status == 1 ? 0 : 1;
      let adIds = [];
      adIds.push(row.id);
      this.$confirm(
        "是否确认" + statusName + "ID为" + adIds + "的数据项?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return advertisementStatus({ids: adIds, status: status});
        })
        .then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        })
        .catch(function () {
        });
    },
    // 审核
    updateAuditorStatus(row, type) {
      if (!type) {
        var statusName = row.auditorStatus == 0 ? "审核" : "撤回";
        var status = row.auditorStatus == 0 ? 1 : 0;
      } else {
        var statusName = "审核不通过";
        var status = 2;
      }
      let adIds = [];
      adIds.push(row.id);
      this.$confirm(
        "是否确认" + statusName + "ID为" + adIds + "的数据项?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return advertisementAudit({ids: adIds, auditorStatus: status});
        })
        .then(() => {
          this.getList();
          this.msgSuccess("修改成功");
        })
        .catch(function () {
        });
    },
    // 图片上传
    async beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (file.type.indexOf("image/") == -1) {
        this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else if (!isLt2M) {
        this.$message.error("图片大小不能超过 2MB!");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.form.file = reader.result;
          this.adImageFile = file;
          this.updataShow = true;
          this.$forceUpdate();
        };
      }
      // 返回false则不会调用默认的上传行为
      return false;
    },
  },
};
</script>

<style lang="scss">
.image-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.image-uploader .el-upload:hover {
  border-color: #409eff;
}

.image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.image {
  width: 178px;
  height: 178px;
  display: block;
}

.ad-img {
  width: 80rpx;
  height: 60rpx;
}
</style>
